<template>
  <editor v-model="textContent" :init="init" :tinymceScriptSrc="tinymceScriptSrc"></editor>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import tinymce from 'tinymce/tinymce' //tinymce默认hidden，不引入不显示
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/themes/silver/theme' // 主题文件
import 'tinymce/icons/default'
import 'tinymce/models/dom'
// tinymce插件可按自己的需要进行导入
import 'tinymce/plugins/accordion' // 列表插件
import 'tinymce/plugins/lists' // 列表插件
import 'tinymce/plugins/advlist' // 有序列表插件
import 'tinymce/plugins/anchor' // 锚点插件
import 'tinymce/plugins/autolink' // 当用户输入有效的完整URL时，autolink插件会自动创建超链接。
import 'tinymce/plugins/link' // 链接
import 'tinymce/plugins/autosave' // 定时自动将编辑内容保存到浏览器本地存储中（Local Storage）
import 'tinymce/plugins/autoresize' // 可拉伸宽度
import 'tinymce/plugins/charmap' // 特殊字符
import 'tinymce/plugins/code' // 查看源码
import 'tinymce/plugins/codesample' // 插入代码
import 'tinymce/plugins/directionality' // 文字方向
import 'tinymce/plugins/emoticons' // 表情符号
import 'tinymce/plugins/emoticons/js/emojis'
import 'tinymce/plugins/fullscreen' //全屏
// import 'tinymce/plugins/help' //帮助
// import 'tinymce/plugins/help/js/i18n/keynav/en.js'
import 'tinymce/plugins/image' // 插入上传图片插件
import 'tinymce/plugins/importcss' //引入自己定义的css文件
import 'tinymce/plugins/insertdatetime' //插入时间日期
import 'tinymce/plugins/nonbreaking' // 空格
import 'tinymce/plugins/pagebreak' //分页
import 'tinymce/plugins/preview' // 预览
import 'tinymce/plugins/quickbars' // 快速工具栏
import 'tinymce/plugins/save' // 保存
import 'tinymce/plugins/searchreplace' //查询替换
import 'tinymce/plugins/table' // 插入表格插件
import 'tinymce/plugins/wordcount' // 字数统计插件
import 'tinymce/plugins/visualblocks' // 块范围显示
// import 'tinymce/plugins/template' //插入模板


const props = defineProps({
  modelValue: String,
  mode: {
    type: String,
    default: 'complexMode'
  },
})
const emit = defineEmits(['update:modelValue'])
const getModeConfig = (): any => {
  switch (props.mode) {
    case 'simpleMode':
      return {
        plugins: 'importcss lists advlist table image autolink formatpainter quickbars charmap',
        toolbar: 'complex-mode fontfamily fontsize forecolor backcolor | bold italic underline strikethrough | alignleft aligncenter alignright | bullist numlist | formatpainter removeformat'
      }
    case 'complexMode':
      return {
        // plugins: 'accordion lists advlist preview fullscreen table importcss image save codesample charmap searchreplace link autolink kityformula-editor formatpainter quickbars',
        // toolbar: ' simple-mode | undo redo | fontfamily fontsize forecolor backcolor bold italic underline strikethrough | blocks alignleft aligncenter alignright alignjustify lineheight outdent indent ltr rtl | bullist numlist | table image link blockquote subscript superscript codesample charmap kityformula-editor | pastetext searchreplace removeformat formatpainter | preview fullscreen save'
        plugins: 'save accordion lists advlist quickbars anchor autolink link autosave charmap wordcount code codesample directionality emoticons fullscreen help image importcss insertdatetime nonbreaking pagebreak preview searchreplace table visualblocks formatpainter kityformula-editor imagetools',
        toolbar: 'save cancel newdocument | accordion accordiontoggle accordionremove | bullist numlist | anchor quicklink link unlink openlink | restoredraft charmap code codesample ltr rtl emoticons fullscreen help addTab image styles insertdatetime nonbreaking pagebreak preview searchreplace table visualblocks wordcount formatpainter kityformula-editor pastetext removeformat'
      }
  }
}
const tinymceScriptSrc = '/tinymce/tinymce.min.js'
const tinymceRef = ref()
const init = {
  // width: 720,
  height: 400,
  language_url: '/tinymce/langs/zh-Hans.js',
  language: 'zh-Hans',
  // 皮肤：这里引入的是public下的资源文件
  skin_url: '/tinymce/skins/ui/oxide',
  // skin_url: 'tinymce/skins/ui/oxide-dark',//黑色系
  // content_css: '/tinymce/skins/content/default/content.css', //内容区域css样式
  content_css: '/my-style.css', //内容区域css样式
  content_style: "p {margin: 5px 0;}",
  plugins: getModeConfig().plugins,
  toolbar: getModeConfig().toolbar,
  external_plugins: {
    'kityformula-editor': '/tinymce/plugins/kityformula-editor/plugin.min.js',
    formatpainter: '/tinymce/plugins/formatpainter/plugin.min.js',
    imagetools: '/tinymce/plugins/imagetools/plugin.js',
    help: '/tinymce/plugins/help/plugin.min.js',
  },
  // 快速工具栏配置，需引入插件 quickbars
  quickbars_selection_toolbar: 'bold italic underline strikethrough bullist numlist anchor link', // 设置 快速选择 触发提供的工具栏 需引入插件  默认 'alignleft aligncenter alignright' 设置为false禁用
  quickbars_insert_toolbar: 'quickimage quicktable quicklink | hr pagebreak', // 设置 快速插入 触发提供的工具栏 需引入插件quickbars 默认 quickimage quicktable 设置为false禁用
  quickbars_image_toolbar: 'alignleft aligncenter alignright',
  save_onsavecallback: function () { alert('已保存'); },
  automatic_uploads: false, // 禁止图片自动上传
  auto_focus: true,
  branding: false,
  // 隐藏菜单栏
  // menubar: false,
  // 是否显示底部状态栏
  // statusbar: false,
  // convert_urls: false,
  resize: true, // 禁止改变大小
  paste_data_images: true,
  font_size_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
  font_family_formats:
    '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats;',
  setup: (editor: any) => {
    console.log(editor);
    tinymceRef.value = editor
    editor.ui.registry.addButton("complex-mode", {
      text: "模式切换",
      tooltip: '切换为复杂模式',
      onAction: function () {
        alert('切换为复杂模式')
      }
    })
    editor.ui.registry.addButton("simple-mode", {
      text: "模式切换",
      tooltip: '切换为简单模式',
      onAction: function () {
        alert('切换为简单模式')
      }
    })
    // editor.ui.registry.addContextToolbar('paragraphlink', {
    //   predicate: (node) => {
    //     return node.nodeName.toLowerCase() === 'p';
    //   },
    //   items: 'quicklink',
    //   position: 'node'
    // })
    // editor.ui.registry.addContextToolbar('textselection', {
    //   predicate: (_node: any) => !editor.selection.isCollapsed(),
    //   items: 'bold italic | bullist numlist',
    //   position: 'selection',
    //   scope: 'node'
    // });
  },
  // 初始化完成
  init_instance_callback: (editor: any) => {
    console.log('初始化完成：', editor)
    editor.on('blur', (_e: any) => {
      alert('失焦保存')
      // var content = tinyMCE.activeEditor.getContent();
    })
    // editor.execCommand('InsertAccordion');
    // editor.execCommand('ApplyOrderedListStyle', false, {
    //   'list-style-type': 'decimal'
    // });
    // editor.execCommand('ApplyUnorderedListStyle', false, {
    //   'list-style-type': 'cjk-decimal'
    // });
    // editor.execCommand('InsertDefinitionList', false, {
    //   'list-item-attributes': { class: 'mylistitemclass' },
    //   'list-attributes': { id: 'mylist' }
    // });
    editor.execCommand('mceListUpdate', false, {
      styles: { 'background-color': 'powderblue' }
    });
    // editor.execCommand('mceListProps')
  },
  // 此处为自定义图片上传处理函数
  images_upload_handler: (blobInfo: any) => new Promise((resolve, reject) => {
    let file = blobInfo.blob()
    // 调接口
    console.log(file, '==file')
    // let url = 'blob:http://127.0.0.1:8000/2c6c7bbe-cb9a-481d-acfe-adc00f2866d5'
    // resolve(url)
  }),
  /* accordion插件配置如下： */
  details_initial_state: 'expanded', // 设置details的初识状态
  details_serialized_state: 'collapsed', // 设置details的预览初识状态
  // 新建文档的默认内容
  newdocument_content: '<details><summary>Accordion summary自定义...</summary><p>Accordion body...</p></details>',
  /* advlist插件配置如下： */
  advlist_bullet_styles: 'disc,circle,square',  // 设置无序列表的类型
  advlist_number_styles: 'decimal,lower-alpha,lower-greek,lower-roman,upper-alpha,upper-roman', // 设置有序列表的类型
  // inline: true,
  menu: { tools: { title: 'Tools', items: 'listprops' } }, // 菜单栏-工具中添加列表设置
  lists_indent_on_tab: true, // 是否按tab键进入新的子列表
  allow_html_in_named_anchor: true, // 不保留锚点，可删除锚点
  // link_default_target: '_self',
  link_default_protocol: 'http',
  link_assume_external_targets: true,
  link_class_list: [
    { title: 'None', value: '' },
    { title: 'External Link', value: 'ext_link' },
    {
      title: 'Internal Links',
      menu: [
        { title: 'Internal Support Link', value: 'int_sup_link' },
        { title: 'Internal Marketing Link', value: 'int_mark_link' },
        { title: 'Other Internal Link', value: 'int_other_link' }
      ]
    }
  ],
  link_context_toolbar: true,
  link_list: [
    { title: '{companyname} Home Page', value: '{companyurl}' },
    { title: '{companyname} Blog', value: '{companyurl}/blog' },
    {
      title: '{productname} Support resources',
      menu: [
        { title: '{productname} Documentation', value: '{companyurl}/docs/' },
        { title: '{productname} on Stack Overflow', value: '{communitysupporturl}' },
        { title: '{productname} GitHub', value: 'https://github.com/tinymce/' }
      ]
    }
  ],
  link_title: false,
  link_quicklink: true,
  link_rel_list: [
    { title: 'No Referrer', value: 'noreferrer' },
    { title: 'External Link', value: 'external' }
  ],
  link_target_list: [
    { title: 'None', value: '' },
    { title: 'Same page', value: '_self' },
    { title: 'New page', value: '_blank' },
    { title: 'Parent frame', value: '_parent' }
  ],
  charmap_append: [
    [0x2615, 'morning coffee'],
    [0x2600, 'sun'],
    [0x2601, 'cloud'],
  ],
  emoticons_append: {
    custom_mind_explode: {
      keywords: ['brain', 'mind', 'explode', 'blown'],
      char: '🤯'
    }
  },
  fullscreen_native: true,
  help_accessibility: false,
  help_tabs: [
    'shortcuts', // the default shortcuts tab
    'keyboardnav', // the default keyboard navigation tab
    'plugins', // the default plugins tab
    {
      name: 'custom1', // new tab called custom1
      title: 'Custom Tab 1',
      items: [
        {
          type: 'htmlpanel',
          html: '<p>This is a custom tab</p>',
        }
      ]
    },
    {
      name: 'versions', // override the default versions tab
      title: 'Custom Versions',
      items: [
        {
          type: 'htmlpanel',
          html: 'This is a custom versions panel.'
        }
      ]
    },
  ],
  a11y_advanced_options: false,
  image_list: [
    { title: 'My image 1', value: 'https://upload-images.jianshu.io/upload_images/5809200-a99419bb94924e6d.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240' },
  ],
  file_picker_types: 'image',
  file_picker_callback: (cb: any, value, meta) => {
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');

    input.addEventListener('change', (e: any) => {
      const file = e.target.files[0];

      const reader: any = new FileReader();
      reader.addEventListener('load', () => {
        /*
          Note: Now we need to register the blob in TinyMCEs image blob
          registry. In the next release this part hopefully won't be
          necessary, as we are looking to handle it internally.
        */
        const id = 'blobid' + (new Date()).getTime();
        console.log(tinymceRef.value, '==tinymceRef.value');
        const blobCache = tinymceRef.value.editorUpload.blobCache;
        const base64 = reader.result.split(',')[1];
        const blobInfo = blobCache.create(id, file, base64);
        blobCache.add(blobInfo);

        console.log(blobInfo, '==blobInfo.blobUri()');
        // 调接口
        // let file = blobInfo.blob()
        // console.log(file, '==file')
        /* call the callback and populate the Title field with the file name */
        cb(blobInfo.blobUri(), { title: file.name });
      });
      reader.readAsDataURL(file);
    });

    input.click();
  },
  image_caption: true,
  image_advtab: true,
  image_description: false,
  image_dimensions: false,
  image_title: true,
  typeahead_urls: false,
  // importcss_append: true,
  importcss_exclusive: false,
  pagebreak_separator: '<!-- my page break -->',
  pagebreak_split_block: true,
  table_border_widths: [
    { title: 'small', value: '1px' },
    { title: 'medium', value: '3px' },
    { title: 'large', value: '5px' },
  ],
  table_toolbar: 'tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol tablecellborderwidth tablecellborderstyle',
  // table_style_by_css: false
  promotion: false,
}
// 组件挂载完毕
onMounted(() => {
  tinymce.init({})
})

const textContent = ref(props.modelValue)
watch(textContent, (newVal) => emit('update:modelValue', newVal))

</script>

<style scoped>
</style>